package com.wiz.common.util;

import java.awt.image.BufferedImage;
import java.util.Hashtable;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

/**
 * 二维码生成工具
 * @author Administrator
 *
 */
public class QRCodeUtil {

	private static final int BLACK = 0xFF000000;
//	private static final int WHITE = 0xb6ddc7;
//	private static final int backColor=new Color(182,221,199).getRGB();
	private static final int WHITE = 0xFFFFFFFF;
	
	public static BufferedImage drawQRCode(String text) throws Exception{
		Hashtable hints = new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		int width = 350;
		int height = 350;
		BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
		int b_width = bitMatrix.getWidth();
		int b_height = bitMatrix.getHeight();
		int minX = width;
		int minY = height;
		int maxX = 0;
		int maxY = 0;
		for (int x = 0; x < b_width; x++) {
			for(int y = 0; y < b_height; y++){
				if(bitMatrix.get(x, y)){
					if(minX>x) minX= x;
					if(maxY<y) maxY = y;
					if(maxX<x) maxX= x;
					if(minY>y) minY = y;
				}
			}
		}
		// 建立图像缓冲器
		BufferedImage qrImage = new BufferedImage(maxX+1-minX, maxY+1-minY, BufferedImage.TYPE_3BYTE_BGR);
		for (int x = 0; x < maxX+1-minX; x++) {
			for (int y = 0; y < maxY+1-minY; y++) {
				qrImage.setRGB(x, y, bitMatrix.get(minX+x, minY+y) ? BLACK : WHITE);
			}
		}
		return qrImage;
	}
	
}
